package com.agile.leetcode.tomcat.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.io.UnsupportedEncodingException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/9 18:13
 */
public class NettyResponse {
    private ChannelHandlerContext ctx;
    private HttpRequest httpRequest;

    public NettyResponse(ChannelHandlerContext ctx, HttpRequest httpRequest) {
        this.ctx = ctx;
        this.httpRequest = httpRequest;
    }
    public void write(String out) {
        if (out == null || out.length()==0){
            return;
        }
        try {
            FullHttpResponse fullHttpResponse=new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    // 将输出值写出 编码为UTF-8
                    Unpooled.wrappedBuffer(out.getBytes("UTF-8")));
            fullHttpResponse.headers().set("Content-Type", "text/html;");
            ctx.write(fullHttpResponse);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }finally {
            ctx.flush();
            ctx.close();
        }
    }

}
